package org.cheetah.core;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.cheetah.core.action.Action;
import org.cheetah.core.action.ActionDefinition;
import org.cheetah.core.action.spi.FromDefinition;

@XmlRootElement(name = "service")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class ServiceDefinition {
	@XmlElementRef
	private List<FromDefinition> from;

	@XmlElementRef
	private List<ActionDefinition> to;

	@XmlAttribute(name = "name")
	private String name;

	@XmlTransient
	private Service registered;

	public ServiceDefinition() {
		to = new ArrayList<ActionDefinition>();
	}

	public ServiceDefinition setName(String name) {
		this.name = name;
		return this;
	}

	public ServiceDefinition addAction(ActionDefinition action) {
		to.add(action);
		return this;
	}

	public ServiceDefinition register() {
		Service svc = new Service(name);
		Service.register(name, svc);

		registered = svc;
		return this;
	}

	public void start() throws Exception {
		if (registered == null) {
			register();
		}

		List<Action> built = new ArrayList<Action>();
		for (ActionDefinition def : to) {
			built.add(def.createAction());
		}

		registered.setPipeline(built);

		if (from != null) {
			for (FromDefinition def : from) {
				def.start(registered);
			}
		}
	}
}
